<script setup>
import {
  Search,
  RefreshLeft,
  Plus,
  Bottom,
  Top,
  Remove,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import request from "../utils/request.js";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import axios from "axios";

const data = reactive({
  // table表格展示的数据
  tableData: [],
  // 添加编辑弹框的数据
  form: {
    // 下面注释的代码可写可不写
    // username: "",
    // password: "",
  },
  addForm:{

  }
});

// 分页功能，模糊查询
const current = ref(1);
const size = ref(4);
const total = ref(0);
const name = ref("");
const showBooks = () => {
  request
    .get("/admin/selectbooklistByPage", {
      params: {
        name: name.value,
        current: current.value,
        size: size.value,
      },
    })
    .then((res) => {
      // res不为空展示数据，为空证明未登录或者过期
      if (res) {
        // 将分页查询到的数据存入数组中
        // console.log(res);
        data.tableData = res.data.records;
        total.value = res.data.total;
      }
    });
};

showBooks();


// 箭头函数

const next_click = (row) => {
  current.value = row;
  // console.log();
  showBooks();
};

const prev_click = (row) => {
  current.value = row;
};

const handleCurrentChange = (row) => {
  current.value = row;
  showBooks();
};

// 重置
const reset = () => {
  name.value = "";
  showBooks();
};

// 添加功能
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
// 点击添加按钮展示弹框
const showForm = () => {
  dialogFormVisible.value = true;
  data.addForm = {}

}
const addBook = () =>{
  request.post("/addBook",data.addForm).then((res)=>{
    if(res.code === "200"){
      dialogFormVisible.value = false
      showBooks()
      ElMessage.success(res.msg)
    }
  })
}

//编辑功能
const dialogFormVisible1 = ref(false);
// 点击编辑按钮展示弹窗，根据传递的参数获取该行的值
const EditBook = (row) => {
  // 单独定义form时进行如下操作，会失去响应式，编辑时无法输入，所以将form加入到data里面
  data.form = JSON.parse(JSON.stringify(row));
  // console.log(row);
  dialogFormVisible1.value = true;
};

const editBook =()=>{
  request.post("/editBook",data.form).then((res)=>{
    if(res.code==="200"){
      ElMessage.success("修改完成")
      dialogFormVisible1.value = false
      showBooks()
    }
  })
}



// 根据id删除用户
const delBook = (row) => {
  request.get("/delBookById/" + row.id).then((res) => {
    if (res.code === "200") {
      ElMessage.success(res.msg);
      // 刷新数据
      showBooks();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 批量删除，利用table组件的多选功能
const delIds = reactive([]); //用于记录要删除的用户的id
const multipleSelection = ref([]); //配合下面的函数使用

// 该函数会记录选择的每行的对象，将对象的id提取出成为一个数组，然后点击批量删除的时候将数组传递给后端进行删除
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  delIds.value = multipleSelection.value.map((v) => v.id);
};
const delBooks = () => {
  if (!delIds.value) {
    ElMessage.error("请先选择要删除的数据");
  } else {
    request.post("/delBookByIds", delIds.value).then((res) => {
      if (res.code === "200") {
        ElMessage.success(res.msg);
        showBooks();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

// 书籍评价
const rightComment = ref(false);
const coData = reactive({
  commentData: [],
});
const showComment = (bookId) => {
  request.get("/selectCommentByBookId/" + bookId).then((res) => {
    if (res.code === "200") {
      coData.commentData = res.data;
      // console.log(coData.commentData);
    }
  });
  rightComment.value = true;
};

//删除评价
const delCommentById = (id, bookId) => {
  request.get("/delCommentById/" + id).then((res) => {
    if (res.code === "200") {
      ElMessage.success(res.msg);
      showComment(bookId);
    }
  });
};

// 图片文件上传之前
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    //只能为图片类型
    // imageUrl=rawFile
    ElMessage.error("请选择图片类型的文件！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("大小不能超过2MB!"); //不能大于2MB
    return false;
  }
  return true;
};


// post方式文件上传到后端,后端用MultipartFile类型接受file，
// 上传完成后直接将返回来的链接赋值给photo，直接显示
const uploadBookPhoto = (param) => {
  const file = new FormData();
  file.append("file", param.file);
  axios.post("/path/uploadBookImg", file).then((res) => {
    // 上传完图片直接显示
    data.addForm.photo = res.data.data
  });
}

const updateBookPhoto = (param) => {
  const file = new FormData();
  file.append("file", param.file);
  axios.post("/path/uploadBookImg", file).then((res) => {
    // 上传完图片直接显示
    data.form.photo = res.data.data
  });
}

// 导出excel表格
const exportUser = () => {
  window.open("http://localhost:8080/exportBooks");
  // request.get("/exportUser").then(res=>{

  // })
};

// 将excel表格导入
// 使用upload组件时。使用action设置url时会遇到跨域问题，所以使用http-request来自定义方法进行请求
const upload = (param) => {
  const file = new FormData();
  file.append("file", param.file);
  axios.post("/path/importBooks", file).then((res) => {
    ElMessage.success(res.msg);
    showUsers();
  });
};
</script>


<template>
  <div>
    <!-- 搜索重置添加 -->
    <div class="right_top">
      <el-input
        v-model="name"
        placeholder="请输入"
        style="width: 300px; padding-right: 5px"
      />
      <!-- 模糊查询，利用双向绑定的name -->
      <el-button type="primary" @click="showBooks">
        <el-icon><Search /></el-icon>
        <span>搜索</span>
      </el-button>
      <!-- 重置 -->
      <el-button type="warning" @click="reset">
        <el-icon><RefreshLeft /></el-icon>
        <span>重置</span>
      </el-button>

      <!-- 导入文件 -->
        <el-upload
          action=""
          :http-request="upload"
          style="display: inline-block"
          :show-file-list="false"
        >
          <el-button type="primary">
            <el-icon><Bottom /></el-icon>
            <span>导入</span>
          </el-button>
        </el-upload>

        <el-button type="primary" @click="exportUser">
          <el-icon><Top /></el-icon>
          <span>导出</span>
        </el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="success" @click="showForm">
        <el-icon><Plus /></el-icon>
        <span>新增</span>
      </el-button>
      <!-- 导入文件
      <el-upload
        action=""
        :http-request="upload"
        style="display: inline-block"
        :show-file-list="false"
      >
        <el-button type="primary">
          <el-icon><Bottom /></el-icon>
          <span>导入</span>
        </el-button>
      </el-upload>

      <el-button type="primary" @click="exportUser">
        <el-icon><Top /></el-icon>
        <span>导出</span>
      </el-button> -->
      <el-button type="danger" @click="delBooks">
        <el-icon><Remove /></el-icon>
        <span>批量删除</span>
      </el-button>
    </div>
    <!-- table表格 -->
    <div class="right_main">
      <el-table
        :data="data.tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="书籍图片" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <img
                :src="scope.row.photo"
                alt=""
                style="width: 100px; height: 80px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bookName" label="书名" width="150" />
        <el-table-column prop="writer" label="作者" width="150" />
        <el-table-column prop="detail" label="书籍详情" width="150" />
        <el-table-column prop="bookPrice" label="价格" width="150" />
        <el-table-column label="操作">
          <!-- 最新版插槽的写法 -->
          <template #default="scope">
            <el-button type="primary" @click="EditBook(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm title="确定删除？" @confirm="delBook(scope.row)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
            <el-button
              text
              @click="showComment(scope.row.id)"
              style="color: blue"
              >该书的相关评价</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 评价 -->
    <el-drawer
      v-model="rightComment"
      title="用户评价"
      direction="rtl"
      size="35%"
    >
      <el-table :data="coData.commentData" height="600px">
        <el-table-column property="name" label="用户名" width="100" />
        <el-table-column property="content" label="评论" width="150" />
        <el-table-column property="time" label="时间" width="150" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-button
                type="danger"
                @click="delCommentById(scope.row.id, scope.row.bookId)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <!-- 分页 -->
    <div class="page">
      <el-pagination
        small
        background
        :pager-count="5"
        layout="prev, pager, next"
        :total="total"
        :page-size="size"
        @current-change="handleCurrentChange"
        class="mt-4"
        @next-click="next_click"
        @prev-click="prev_click"
      />
    </div>
    <!-- 添加的弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="Add Book">
      <el-form :model="data.addForm" status-icon>
        <el-form-item
          label="上传封面"
          :label-width="formLabelWidth"
          prop="photo"
        >
        <div class="bookPhoto" style="width: 180px; height: 180px; border:1px solid black">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadBookPhoto"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="1"
          >
            <img
              v-if="data.addForm.photo"
              :src="data.addForm.photo"
              class="avatar"
              style="width: 180px; height: 180px"
            />
            <el-icon v-else class="avatar-uploader-icon" size="20"><Plus /></el-icon>
          </el-upload>
          </div>
        </el-form-item>
        <el-form-item
          label="书名"
          :label-width="formLabelWidth"
          prop="bookName"
        >
          <el-input
            v-model="data.addForm.bookName"
            autocomplete="off"
            placeholder="请输入书名"
          />
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth" prop="writer">
          <el-input
            v-model="data.addForm.writer"
            autocomplete="off"
            placeholder="请输入作者"
          />
        </el-form-item>
        <el-form-item label="详情" :label-width="formLabelWidth" prop="detail">
          <el-input
            v-model="data.addForm.detail"
            autocomplete="off"
            placeholder="请输入详情"
          />
        </el-form-item>
        <el-form-item
          label="价格"
          :label-width="formLabelWidth"
          prop="bookPrice"
        >
          <el-input
            v-model="data.addForm.bookPrice"
            autocomplete="off"
            placeholder="请输入价格"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addBook"> 添加 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑的弹出框 -->
    <el-dialog v-model="dialogFormVisible1" title="Update Book">
      <el-form :model="data.form" status-icon>
        <el-form-item
          label="封面"
          :label-width="formLabelWidth"
          prop="photo"
        >
        <div class="bookPhoto" style="width: 180px; height: 180px; border:1px solid black">
          <el-upload
            class="avatar-uploader"
            :http-request="updateBookPhoto"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="1"
          >
            <img
              v-if="data.form.photo"
              :src="data.form.photo"
              class="avatar"
              style="width: 180px; height: 180px"
            />
            <el-icon v-else class="avatar-uploader-icon" size="20"><Plus /></el-icon>
          </el-upload>
          </div>
        </el-form-item>
        
        <el-form-item
          label="书名"
          :label-width="formLabelWidth"
          prop="bookName"
        >
          <el-input
            v-model="data.form.bookName"
            autocomplete="off"
            placeholder="请输入书名"
          />
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth" prop="writer">
          <el-input
            v-model="data.form.writer"
            autocomplete="off"
            placeholder="请输入作者"
          />
        </el-form-item>
        <el-form-item label="详情" :label-width="formLabelWidth" prop="detail">
          <el-input
            v-model="data.form.detail"
            autocomplete="off"
            placeholder="请输入详情"
          />
        </el-form-item>
        <el-form-item
          label="价格"
          :label-width="formLabelWidth"
          prop="bookPrice"
        >
          <el-input
            v-model="data.form.bookPrice"
            autocomplete="off"
            placeholder="请输入价格"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="editBook"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.page {
  padding-top: 20px;
}
</style>